package com.itouch.bracelet.activity;

import io.rong.imkit.RongIM;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.BaseResult;
import com.itouch.bracelet.bean.LoginResult;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.JsonAndPhpUtil;
import com.itouch.util.StringUtils;

public class RegisterActivity extends BaseActivity implements OnClickListener {

	private EditText username;
	private EditText phone;
	private TextView phoneCodeGet;
	private EditText phoneCode;
	private EditText password;
	private EditText repassword;
	private EditText deviceCode;
	private TextView deviceCodeGet;
	private TextView register;
	private TextView haveId;
	private TextView lostPs;
	private static final int REQUESE_QR = 0x1234;
	private ScrollView scrollview;
	private TextView nextPage;

	@Override
	protected int setContentViewById() {
		return R.layout.activity_register;
	}

	@Override
	protected void initViews() {
		
		scrollview=(ScrollView) findViewById(R.id.scrollview);
		nextPage = (TextView) findViewById(R.id.nextpage);
		username = (EditText) findViewById(R.id.username);
		phone = (EditText) findViewById(R.id.phone);
		phoneCodeGet = (TextView) findViewById(R.id.phone_code_get);
		phoneCode = (EditText) findViewById(R.id.phone_code);
		password = (EditText) findViewById(R.id.password);
		repassword = (EditText) findViewById(R.id.repassword);
		deviceCode = (EditText) findViewById(R.id.device_code);
		deviceCodeGet = (TextView) findViewById(R.id.device_code_get);
		register = (TextView) findViewById(R.id.register);
		haveId = (TextView) findViewById(R.id.have_id);
		lostPs = (TextView) findViewById(R.id.lost_ps);
		lostPs .setOnClickListener(this);
		haveId.setOnClickListener(this);
		register.setOnClickListener(this);
		deviceCodeGet.setOnClickListener(this);
		phoneCodeGet.setOnClickListener(this);
		
		nextPage .setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		Intent it = null;
		switch (v.getId()) {
		case R.id.have_id:
			this.finish();
			break;
		case R.id.nextpage:
			if(scrollview!=null){
				scrollview.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
			}
			
			break;
		case R.id.register:
			String nameString=username.getText().toString();
			String phoneString = phone.getText().toString();
			String codeString =phoneCode.getText().toString();
			String passwordString=password.getText().toString();
			String repasswordString=repassword.getText().toString();
			String deviceCodeString =deviceCode.getText().toString();
			
			if(nameString.length()<2){
				Toast.makeText(context, R.string.register_name, Toast.LENGTH_LONG).show();
				return;
			}
			
			if(phoneString.length()<11){
				Toast.makeText(context, R.string.register_phone, Toast.LENGTH_LONG).show();
				return;
			}
			
			if(passwordString.length()<5){
				Toast.makeText(context, R.string.register_password, Toast.LENGTH_LONG).show();
				return;
			}
			
			if(!passwordString.equals(repasswordString)){
				Toast.makeText(context, R.string.register_repassword, Toast.LENGTH_LONG).show();
				return;
			}
//			if(deviceCodeString.length()<8){
//				Toast.makeText(context, R.string.register_device, Toast.LENGTH_LONG).show();
//				return;
//			}
			
			new LoginAsync(nameString, phoneString, codeString, passwordString, deviceCodeString).execute();
			
			break;
		case R.id.lost_ps:
			it = new Intent(context, LostPSActivity.class);
			startActivity(it);
			this.finish();
			break;
		case R.id.device_code_get:
			//获取设备号
			it = new Intent(context, QrCodeActivity.class);
			startActivityForResult(it, REQUESE_QR);
			
			break;
		case R.id.phone_code_get:
			break;

		default:
			break;

		}

	}

	

	/**
	 * 大人注册的接口  Async实现
	 * @param name  用户名	
	 * @param phone 用户手机	
	 * @param code  验证码
	 * @param password  密码	
	 * @param deviceCode  设备号  （非必选）
	 */
	class LoginAsync extends AsyncTask<String, String, String> {

		public String name;public String phone;public String code ;public String password;public String deviceCode;


		public LoginAsync(String name, String phone, String code,
				String password, String deviceCode) {
			super();
			this.name = name;
			this.phone = phone;
			this.code = code;
			this.password = password;
			this.deviceCode = deviceCode;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			show();
		}

		@Override
		protected String doInBackground(String... params) {
			List<NameValuePair> lists = new ArrayList<NameValuePair>();
			
			lists.add(new BasicNameValuePair("name", name));
			lists.add(new BasicNameValuePair("password", password));
			lists.add(new BasicNameValuePair("validCode", code));
			lists.add(new BasicNameValuePair("deviceType", "2"));
			lists.add(new BasicNameValuePair("mobile", phone + ""));
			lists.add(new BasicNameValuePair("deviceNo", deviceCode + ""));
			lists.add(new BasicNameValuePair("hospitalNo",   "123"));
			String ss = JsonAndPhpUtil.postHttpData(Constants.REGISTER,
					lists, context);
			 Log.i("REGISTER", "REGISTER" + ss);
			return ss;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			disMiss();
			Log.e("REGISTER", "REGISTER" + result);
			if (!StringUtils.isNull(result)) {
				BaseResult a = new Gson().fromJson(result, LoginResult.class);
				if (a != null && a.isFlag()) {
					Toast.makeText(context,
							R.string.register_ok,
							Toast.LENGTH_LONG).show();
					RegisterActivity.this.finish();
				} else {
					String message = a.getMsg();
					Toast.makeText(context, message + "", Toast.LENGTH_LONG)
							.show();
				}
			} else {
				// 网络失败
				Toast.makeText(context, "请求失败，请稍后再试..", Toast.LENGTH_LONG)
						.show();
			}
		}
	}
	
	
	
	
	
	
	/**
	 * 大人注册的接口  volley实现
	 * @param name  用户名	
	 * @param phone 用户手机	
	 * @param code  验证码
	 * @param password  密码	
	 * @param deviceCode  设备号  （非必选）
	 */
	
	private void registration(String name,String phone,String code ,String password,String deviceCode) {
		show();
		RequestQueue requestQueue = Volley.newRequestQueue(this);
//			http://122.224.91.58:6599/handchain/mobi/registration/Registration?name=帅气爸&password=666666&deviceType=2&mobile=13757982221&deviceNo=28&hospitalNo=123
		Uri.Builder builder = Uri.parse(Constants.REGISTER)
				.buildUpon();
		builder.appendQueryParameter("name", name);
		builder.appendQueryParameter("password", password);
		builder.appendQueryParameter("validCode", code);
		builder.appendQueryParameter("deviceType", "2");
		builder.appendQueryParameter("mobile", phone + "");
		builder.appendQueryParameter("deviceNo", deviceCode + "");
		builder.appendQueryParameter("hospitalNo",   "123");
		Log.d("REGISTER",
				"REGISTER==POST" + builder.toString());
		JsonObjectRequest joq = new JsonObjectRequest(
				Request.Method.GET, 
		builder.toString(),null, 
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						disMiss();
						Log.d("REGISTER",
								"REGISTER" + arg0.toString());
						try {
							BaseResult a = new Gson().fromJson(
									arg0.toString(), BaseResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								Toast.makeText(context,
										R.string.register_ok,
										Toast.LENGTH_LONG).show();
								RegisterActivity.this.finish();
							} else {
								Toast.makeText(context,
										a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						disMiss();
						Toast.makeText(context,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});
		requestQueue.add(joq);
	}

	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==this.REQUESE_QR&&resultCode==RESULT_OK&&data!=null){
			String code=data.getStringExtra("code");
			if(deviceCode!=null){
				deviceCode.setText(code);
			}
		}
	}
	
	
	
	@Override
	protected void initData() {

	}

	class DelayTask extends AsyncTask<Integer, String, String> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Integer... arg0) {
			try {
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			// startActivity(new Intent(context, LoginActivity.class));
			// RegisterActivity.this.finish();
		}

	}

}
